/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年7月31日
 */
package com.massyframework.beanskin.runtime.service.adapt;

import java.util.List;
import java.util.Set;

import com.massyframework.beanskin.ModuleEvent;
import com.massyframework.beanskin.ModuleListener;
import com.massyframework.beanskin.ModuleDestoryingEvent;
import com.massyframework.beanskin.assembly.Assembly;
import com.massyframework.beanskin.assembly.AssemblyContext;
import com.massyframework.beanskin.assembly.AssemblyContextSupport;
import com.massyframework.beanskin.service.ServiceTracker;
import com.massyframework.beanskin.service.adapt.AdaptObjectFactory;
import com.massyframework.beanskin.service.adapt.AdaptObjectFactoryRepository;

/**
 * @author huangkh
 *
 */
public class DefaultAdaptObjectFactoryRepository extends AssemblyContextSupport
	implements AdaptObjectFactoryRepository, ModuleListener {

	private AdaptObjectFactoryTracker customizer = new AdaptObjectFactoryTracker();
	@SuppressWarnings("rawtypes")
	private ServiceTracker<AdaptObjectFactory> tracker;
	
	/**
	 * 
	 */
	public DefaultAdaptObjectFactoryRepository() {
		
	}

	@Override
	public Set<Class<?>> getAdaptTypes(Class<?> hostType) {
		return this.customizer.getAdaptTypes(hostType);
	}

	@Override
	public <A> List<AdaptObjectFactory<A>> getAdaptObjectFactories(Class<A> adaptType, Class<?> hostType) {
		return this.customizer.getAdaptObjectFactories(adaptType, hostType);
	}
	

	@Override
	public void onEvent(ModuleEvent event) {
		if (event instanceof ModuleDestoryingEvent) {
			ClassLoader classLoader = event.getModule().getModuleClassLoader();
			this.customizer.clearClassLoader(classLoader);
		}		
	}

	@Override
	protected synchronized void bindAssemblyContext(AssemblyContext context) {
		if (this.tracker == null) {
			super.bindAssemblyContext(context);
			Assembly assembly = context.getAssociatedAssembly();
			
			this.tracker = new ServiceTracker<>(assembly, AdaptObjectFactory.class, null, this.customizer);
			this.tracker.open();
		}
	
	}

	@Override
	protected synchronized void unbindAssemblyContext(AssemblyContext context) {
		if (this.tracker != null) {
			this.customizer.clearAll();
			this.tracker.close();
			this.tracker = null;			
			super.unbindAssemblyContext(context);
		}
	}

	
}
